<?php
// Module Body

function mailman_sendmail_generate(&$submitteddata) {
	global $cfg;

	$data = $submitteddata[0];
	$domalias = $submitteddata[1];
	$userdom = $submitteddata[2];

	$newfile['alias'] .= "\n## Mailman Mailing lists\n";
	$newfile['virtusertable'] .= "\n## Mailman Mailing lists\n";

	$dbp = mysql_query('SELECT domain, listname FROM mailman WHERE action = ""');
	while($data = mysql_fetch_array($dbp)) {
		$name = strtolower($data['listname']);
		$newfile['alias'] .= $name.": \"|".$cfg['mm_wrap']." post $name\"\n";
		$newfile['alias'] .= $name."-admin: \"|".$cfg['mm_wrap']." admin $name\"\n";
		$newfile['alias'] .= $name."-bounces: \"|".$cfg['mm_wrap']." bounces $name\"\n";
		$newfile['alias'] .= $name."-confirm: \"|".$cfg['mm_wrap']." confirm $name\"\n";
		$newfile['alias'] .= $name."-join: \"|".$cfg['mm_wrap']." join $name\"\n";
		$newfile['alias'] .= $name."-leave: \"|".$cfg['mm_wrap']." leave $name\"\n";
		$newfile['alias'] .= $name."-owner: \"|".$cfg['mm_wrap']." owner $name\"\n";
		$newfile['alias'] .= $name."-request: \"|".$cfg['mm_wrap']." request $name\"\n";
		$newfile['alias'] .= $name."-subscribe: \"|".$cfg['mm_wrap']." subscribe $name\"\n";
		$newfile['alias'] .= $name."-unsubscribe: \"|".$cfg['mm_wrap']." unsubscribe $name\"\n";

		$ttmp = mysql_query('SELECT id, domain FROM domains WHERE id="'.$data['domain'].'"');
		if ($tttmp=mysql_fetch_assoc($ttmp)) {
			$domainname = strtolower($tttmp['domain']);
			$newfile['virtusertable'] .= $name."@".$domainname." ".$name."\n";
            $newfile['virtusertable'] .= $name."-admin@".$domainname." ".$name."-admin\n";
            $newfile['virtusertable'] .= $name."-bounces@".$domainname." ".$name."-bounces\n";
            $newfile['virtusertable'] .= $name."-confirm@".$domainname." ".$name."-confirm\n";
            $newfile['virtusertable'] .= $name."-join@".$domainname." ".$name."-join\n";
            $newfile['virtusertable'] .= $name."-leave@".$domainname." ".$name."-leave\n";
            $newfile['virtusertable'] .= $name."-owner@".$domainname." ".$name."-owner\n";
            $newfile['virtusertable'] .= $name."-request@".$domainname." ".$name."-request\n";
            $newfile['virtusertable'] .= $name."-subscribe@".$domainname." ".$name."-subscribe\n";
            $newfile['virtusertable'] .= $name."-unsubscribe@".$domainname." ".$name."-unsubscribe\n";

			//add proper virtusertable entries
			if(!in_array($name, $domalias[$data['domain']])) {
				$newfile['virtusertable'] .= $name."@".$userdom[$data['id']]." ".$name."\n";
				//add alias to list
				$domalias[$data['id']][] = $name;
			}

			if(!in_array($name.'-admin', $domalias[$data['domain']])) {
				$newfile['virtusertable'] .= $name.'-admin'."@".$userdom[$data['id']]." ".$name.'-admin'."\n";
				//add alias to list
				$domalias[$data['id']][] = $name.'-admin';
			}

			if(!in_array($name.'-request', $domalias[$data['domain']])) {
				$newfile['virtusertable'] .= $name.'-request'."@".$userdom[$data['id']]." ".$name.'-request'."\n";
				//add alias to list
				$domalias[$data['id']][] = $name.'-request';
			}

			if(!in_array($name.'-owner', $domalias[$data['domain']])) {
				$newfile['virtusertable'] .= $name.'-owner'."@".$userdom[$data['id']]." ".$name.'-request@'.$userdom[$data['id']]."\n";
				//add alias to list
				$domalias[$data['id']][] = $name.'-owner';
			}
		}
	}
	return $newfile;
}

function mailman_add_lang(&$data) {
	global $T;
	switch($data['lang']) {
		default:
			/*if ($data['domaindata']['mm']) {
				$T['domain']['mailman'] = 'Mailing Lists';
			}*/
			$T['menu']['mailman'] = 'Mailing Lists';

			$T['Number of Mailing Lists'] = 'Number of Mailing Lists';
			$T['Mailing Lists'] = 'Mailing Lists';
			$T['err']['Not enough Mailing Lists.'] = 'Not enough Mailing Lists.';
			break;
	}
}

function mailman_add_menu(&$data) {
	global $menu;

	if ($data['domaindata']['mm']) {
		$menu['domain'][] = 'mailman';
	}
}

function mailman_add_cfg(&$cfg) {
    if(!isset($cfg['mm_wrap'])){
        $cfg['mm_wrap']		= '/home/mailman/mail/wrapper';
    	$cfg['mm_maxlists']	= 5;
    }
	if(!isset($cfg['prog']['newlist'])){
        $cfg['prog']['newlist']	= '/var/mailman/bin/newlist';
        $cfg['prog-req']['newlist'] = false;
        $cfg['prog-desc']['newlist'] = "newlist is used to delete files.";
    }
	if(!isset($cfg['prog']['rmlist'])){
        $cfg['prog']['rmlist']	= '/var/mailman/bin/rmlist';
        $cfg['prog-req']['rmlist'] = false;
        $cfg['prog-desc']['rmlist'] = "rmlist is used to delete mailman mailing lists.";
    }
}

function mailman_reseller_settings(&$data) {
	global $T;
	if (isset($data['resellerdata']['mm'])) {
		$val = $data['resellerdata']['mm'];
	} elseif (isset($data['data']['mm'])) {
		$val = $data['data']['mm'];
	}
	if ($data['userdata']['level'] < 2) {
		$value = '<input type="text" name="data[mm]" size="5" maxlength="255" value="';
		if ($val != -1) {
			$value .= intval($val);
		}
		$value .= '" id="mm" onchange="document.getElementById(\'mmcheck\').checked = false;">&nbsp;<input type=checkbox id="mmcheck" name="data[mm]" value="-1" onclick="document.getElementById(\'mm\').value = \'\'"';
		if ($val == -1) {
			$value .= ' checked"';
		}
		$value .= '>'.$T['Unlimited'];
	} else {
		$value = (($val == -1) ? $T['Unlimited'] : intval($val));
	}
	$data['entries'][] = Array('name' => $T['Number of Mailing Lists'], 'value' => $value);
}

function mailman_get_infotable(&$ret) {
	global $T;
	$current = Array('label' => $T['Mailing Lists'], 'fieldname' => 'mm', 'url' => 'mm');
	$ret['entries'][] = $current;
}

function mailman_domain_settings(&$data) {
	global $T;
	if (isset($data['domaindata']['mm'])) {
		$val = $data['domaindata']['mm'];
	} elseif (isset($data['data']['mm'])) {
		$val = $data['data']['mm'];
	}
	if ($data['userdata']['level'] < 3) {
		$value = '<input type="text" name="data[mm]" size="5" maxlength="255" value="';
		if ($val != -1) {
			$value .= intval($val);
		}
		$value .= '" id="mm" onchange="document.getElementById(\'mmcheck\').checked = false;">&nbsp;<input type=checkbox id="mmcheck" name="data[mm]" value="-1" onclick="document.getElementById(\'mm\').value = \'\'"';
		if ($val == -1) {
			$value .= ' checked"';
		}
		$value .= '>'.$T['Unlimited'];
	} else {
		$value = (($val == -1) ? $T['Unlimited'] : intval($val));
	}
	$data['entries'][] = Array('name' => $T['Number of Mailing Lists'], 'value' => $value);
}

function mailman_set(&$data) {
	set_property('mm', $data['mm'], $data['id'], 'mm');
}

function mailman_fetch(&$data) {
	if ($data['type'] == 'reseller') {
		$where = substr($data['where'],0,5);
	} else {
		$where = $data['where'];
	}
	$mm = get_property('mm', $where, 'mm');
	$data['name'][] = 'mm';
	$data['value'][] = $mm;
	return true;
}

function mailman_fetch_alloc(&$data) {
	$where = $data['where'];
	if ($where == 0) {
		$SQL = 'SELECT sum(properties.value) as mm FROM properties WHERE properties.value != -1 AND properties.name = "mm"';
		if ($res = mysql_query($SQL)) {
			if (mysql_num_rows($res)) {
				$row = mysql_fetch_array($res);
				$mm = $row['mm'];
			}
		}
	} elseif (strlen($where) == 5) {
		$SQL = 'SELECT sum(properties.value) as mm FROM properties inner join domains ON properties.id = domains.id WHERE domains.owner = '.$where.' AND properties.value != -1 AND properties.name = "mm"';
		if ($res = mysql_query($SQL)) {
			if (mysql_num_rows($res)) {
				$row = mysql_fetch_array($res);
				$mm = $row['mm'];
			}
		}
	} else {
		$mm = get_property('mm', $where, 'mm');
	}
	$data['name'] = 'mm';
	$data['value'] = $mm;
	return true;
}

function mailman_fetch_total(&$data) {
	$where = $data['where'];
	if ($where == 0) {
		$where = '%';
	} elseif (strlen($where) == 5) {
		$where = substr($where,0,5).'%';
	}
	$SQL = 'SELECT COUNT(*) AS mm FROM mailman WHERE domain LIKE "'.$where.'"';
	if ($res = mysql_query($SQL)) {
		if (mysql_num_rows($res)) {
			$row = mysql_fetch_array($res);
			$mm = $row['mm'];
		} else {
			$mm = 0;
		}
	} else {
		$mm = 0;
	}
	$data['name'] = 'mm';
	$data['value'] = $mm;
	return true;
}

function mailman_check(&$data) {
	$mm = get_property('mm', $data['id'], 'mm');
	if ($mm == $data['mm']) {
		return '';
	} else {
		return 'change';
	}
}

function mailman_domain_check(&$data) {
	global $T;
	$res =  Array();
	$mm = get_property('mm', $data['id'], 'mm');
	if ($mm != '' && $mm != $data['mm']) {
		$res['change'] = 'change';
	}
	$reseller_total = fetchdata('mm','reseller', substr($data['id'],0,5));
	$reseller_total = $reseller_total['mm'];
	$reseller_alloc = fetchdata('mm','alloc', substr($data['id'],0,5));
	$reseller_alloc = $reseller_alloc['mm'];
	$domain_alloc = fetchdata('mm','domain', $data['id']);
	$domain_alloc = $domain_alloc['mm'];
	$available_links = $reseller_total - $reseller_alloc + $domain_alloc;
	if (($reseller_total != -1) && (($data['mm'] > $available_links) || $data['mm'] == -1)) {
		$res['error'] = $T['err']['Not enough Mailing Lists.'];
	}
	return $res;
}

function mailman_domain_manage(&$data) {
	global $T, $cfg, $rx;
	$cp = $data['_cp'];
	$url = $data['_url'];
	$action = $data['_action'];
	$confirm = $data['_confirm'];
	$userdata = $data['_userdata'];
	$personaldata = $data['_personaldata'];
	$domaindata = $data['_domaindata'];
	$resellerdata = $data['_resellerdata'];
	$cp = $data['_cp'];
	$url = $data['_url'];
	$action = $data['_action'];
	$confirm = $data['_confirm'];
	$current_url = $data['_current_url'];
	// Init vars
	$i = 0;
	$j = 0;
	$k = 0;
	unset($done);
	unset($userlist);
	unset($error);
	$number = $domaindata['id'];

	// Establish domain prefix
	$domainname=explode('.',$domaindata['domain']);
	$domainprefix=$domainname[0];

// Get current domain's user list
/* not used here
$dbp = mysql_query("SELECT username FROM users WHERE id=".$domaindata['id']);

while ($tmp = mysql_fetch_array($dbp))
    $userlist[$j++] = $tmp['username'];
*/

// If data is set (i.e the submit button has been hit)
if ((isset($data['name']) OR $action == 'remove') && $confirm) {
	// kill demo users (return error)
	if ($userdata['type'] == "demo") {
		$error[] = $T['err']['demo user'];
	} else {

	    // remove spaces and slashes.
    	if ($action != 'remove') {
        	while (list($key, $val) = each($data))
            	$data[$key] = trim(stripslashes($val));
	        reset($data);
    	}

		// prepend domain if configured
    	if ($cfg['prepend_domain_to_maillist']) {
    		$nametmp = $data['name'];
		    $data['name'] = $domainprefix . "-" . $nametmp;
		}

    	// limit name to 25 characters max
	    $data['name'] = substr($data['name'],0,25);

    	// create database
 	   if ($action == 'create') {
        	// Check database name
	        if (!eregi($rx['list'],$data['name'])) {
    	        $error[$i++] = $T['err']['mm']['name'];
        	}

	        // Name is free?
    	    $dbp = mysql_query('SELECT listname FROM mailman WHERE listname = "'.$data['name'].'"');
        	if(mysql_num_rows($dbp)>0) {
	            $error[$i++] = $T['err']['mm']['exists'];
	        }

	        // User not over it's limit?
			//	$dbp = mysql_query('SELECT listname FROM mailman WHERE domain = '.$number);
			$tmp = fetchdata("mm","total",$domaindata['id']); $tmp = intval($tmp['mm']);

			//	if(mysql_num_rows($dbp)>=$cfg['mm_maxlists'])
			if (($tmp>=$domaindata['mm']) && ($domaindata['mm'] != -1)) {
    	        $error[$i++] = $T['err']['mm']['maxlist'].$domaindata['mm'];
			}

	        // Verify password
    	    if (!eregi($rx['pass'],$data['password'])) {
        	    $error[$i++] = $T['err']['mm']['password'];
			}

	        if(!$error) {
    	        mysql_query('INSERT INTO mailman (domain, listname, admin, password, action) VALUES("'.$number.'", "'.$data['name'].'", "'.$data['admin'].'", ENCODE("'.$data['password'].'", "'.$cfg['key'].'"), "c")');
        	    $done[++$k] = $T['listcreate'].' '.$data['name'];
            	commit('scan');
	        }
	    } elseif ($action == 'remove') {
    	    // update database(s)
	    	// remove database

    	    // Check database name
        	if (!eregi($rx['num'],$data['id'])) {
	            $error[$i++] = $T['err']['mm']['id'];
        	}

	        // if no errors, update user's password
    	    if (!$error) {
        	    mysql_query('UPDATE mailman SET action = \'r\' WHERE id = '.$data['id'].' AND domain = '.$number);
            	$done[++$k] = $T['listremove'];
	            commit('scan');
    	    }
	    }

    }
   	if ($error) {
       	echo "<br>&nbsp;&nbsp;� ".implode("<br>\n&nbsp;&nbsp;� ",$error)."<br>\n";
	}
    if ($done) {
   	    echo "<br>&nbsp;&nbsp;� ".implode("<br>\n&nbsp;&nbsp;� ",$done)."<br>\n";
   	}

} elseif (isset($data['name']) OR $action == 'remove') {
	// prepend domain if configured
    if ($cfg['prepend_domain_to_maillist']) {
   		$nametmp = $data['name'];
    	$data['name'] = $domainprefix . "-" . $nametmp;
	}
	?>
	<blockquote>
	<form action="<?=$current_url;?>" method="post" name="webcp1" onSubmit="submitonce(this);">
		&nbsp;&nbsp;� <?=$T['really '.$action];?><b><?=$data['name'];?></b><br>
	&nbsp;&nbsp;&nbsp;<input type="submit" value="<?=$T['yes'];?>">
	<?
		foreach ($data as $key => $val) {
		echo '<input type="hidden" name="data['.$key.']" value="'.$data[$key].'">';
	}
	?>
		<input type="hidden" name="action" value="<?=$action;?>">
		<input type="hidden" name="confirm" value="true">
		</form>
		</blockquote>
		<?
	}


if ($userdata['level'] < 4) {
?>
<br />
<form action="<?=$current_url;?>" method="post" name="webcp" onSubmit="submitonce(this);">
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" summary="" width="500">
    <tr>
        <td>
        <b class="big"><?=$T['list Creation'];?></b>
        <table border="0" cellpadding="0" cellspacing="0" summary="" class="tblbg">
            <tr>
                <td>
                <table border="0" cellspacing="1" summary="">
                    <tr>
                        <td class="row2"><b><?=$T['list Name'];?></b></td>
                        <td class="row2"><b><?=$T['Password'];?></b></td>
                        <td class="row2"><b><?=$T['Owner E-Mail'];?></b></td>
                    </tr>
                    <tr>
                        <td class="row1" nowrap><?=(($cfg['prepend_domain_to_maillist']) ? $domainprefix."-" : "");?><input type="text" name="data[name]" size="20" maxlength="25"></td>
                        <td class="row1"><input type="text" name="data[password]" size="20" maxlength="25"></td>
                        <td class="row1"><input type="text" name="data[admin]" size="20" maxlength="255"></td>
                    </tr>
                </table>
                </td>
            </tr>
        </table><br>
        <input type="hidden" name="action" value="create">
        <div align="right"><input type="submit" value="<?=$T['Create Mailing'];?>"></div>
        </td>
    </tr>
</table>
</div></form><br><br>
<?
}

$dbp = mysql_query('SELECT * FROM mailman WHERE action != "r" AND domain = '.$number);
if (mysql_num_rows($dbp)) { ?>
<div align="center">
<table border="0" cellpadding="0" cellspacing="0" summary="" width="500">
    <tr>
        <td>
        <b class="big"><?='Mailing list Management';?></b>
        <table border="0" cellpadding="0" cellspacing="0" summary="" class="tblbg">
            <tr>
                <td>
                <table border="0" cellspacing="1" summary="">
                    <tr>
                        <td class="row2"><b>&nbsp;<?=$T['list Name'];?>&nbsp;</b></td>
                        <td class="row2"><b>&nbsp;<?=$T['Owner E-Mail'];?>&nbsp;</b></td>
			<td class="row2"><b>&nbsp;</b></td>
                        <td class="row2">&nbsp;</td>
                    </tr>
                    <?
                    while ($dbdata = mysql_fetch_array($dbp)) {
                        ?>
                    <tr>
                        <td class="row1"><i><?=$dbdata['listname'];?></i></td>
                        <td class="row1"><i><?=$dbdata['admin'];?></i></td>
<?//						<td class="row1">&nbsp;<a href="http://<?=$domaindata['host'];?>.<?=$domaindata['domain'];?>/mailman/admin/<?=$dbdata['listname'];?>" target="_new"><img src="icon/maillist16.gif" border="0" width=15" height="15" alt="<?=$T['Admin List'];?>" /></a>&nbsp;</td>
?>
                      <td class="row1">&nbsp;<a href="/mailman/admin/<?=$dbdata['listname'];?>" target="_new"><img src="icon/maillist16.gif" border="0" width=15" height="15" alt="<?=$T['Admin List'];?>" /></a>&nbsp;</td>
			<td class="row1">&nbsp;<a href="<?=$current_url;?>&action=remove&data[id]=<?=$dbdata['id'];?>&data[name]=<?=$dbdata['listname'];?>"><img src="icon/remove.gif" border="0" width="15" height="15" alt="Remove" /></a>&nbsp;</td>
                    </tr>
                    <? } ?>
                </table>
                </td>
            </tr>
        </table><br>
        </td>
    </tr>
</table>
</div>
<?
	}
}

function mailman_update(&$data) {
	global $cfg, $userchange;
	// Check Mailman Table

	$dbp = mysql_query('SELECT id, domain, listname, admin, DECODE(password, "'.$cfg['key'].'") AS password, action FROM mailman WHERE action != ""');
	while ($data = mysql_fetch_assoc($dbp)) {
		if($data['action'] == 'c') {
			if(strlen($data['password'])<3) {
				mt_srand(time());
				$data['password'] = mt_rand(111111, 999999999);
			}
			if ($cfg['prog']['newlist'] != '') {
				$ttmp = mysql_query('SELECT id, domain FROM domains WHERE id="'.$data['domain'].'"');
				if ($tttmp=mysql_fetch_assoc($ttmp)) {
					exec($cfg['prog']['newlist'].' "'.$data['listname'].'@'.$tttmp['domain'].'" "'.$data['admin'].'" "'.$data['password'].'"');
				} else {
					exec($cfg['prog']['newlist'].' "'.$data['listname'].'" "'.$data['admin'].'" "'.$data['password'].'"');
				}
				mysql_query('UPDATE mailman SET action = "" WHERE id = "'.$data['id'].'"');
				// interactive dump
			webcp_log(3,0,'webcp.php',"Mailman list ".$data['listname']." created",0,$echo);
			} else {
				webcp_log(2,0,'webcp.php',"Mailman list ".$data['listname']." creation failed!",0,$echo);
			}
			$userchange = TRUE;
		}
		elseif($data['action'] == 'r') {
			if ($cfg['prog']['newlist'] != '') {
				exec($cfg['prog']['rmlist'].' -a '.$data['listname']);
				mysql_query('DELETE FROM mailman WHERE id = '.$data['id']);
				// interactive dump
			webcp_log(3,0,'webcp.php',"Mailman list ".$data['listname']." removed",0,$echo);
		} else {
			webcp_log(2,0,'webcp.php',"Mailman list ".$data['listname']." removal failed!",0,$echo);
		}
			$userchange = TRUE;
		}
	}
}

function mailman_generate_host_conf(&$data) {
	global $cfg;
	unset($search);
	unset($replace);

	// Generate mod_cband configuration
	// open virthost.mailman.httpd.tpl
	$file = $cfg['basedir']."/httpd/templates/mailman.httpd.tpl";
	$mailman_conf = stripslashes(file_get_contents($file));

	$search[] = "{MAILMANCGI}";
	$replace[] = $cfg['mm_cgibin'];

	$search[] = "{MAILMANARCH}";
	$replace[] = $cfg['mm_archive'];

    $mailman_conf = str_replace($search, $replace, $mailman_conf);

	return $mailman_conf;
}

function  mailman_template(&$ret) {
	global $cfg;

	$template['title'] = 'mailman';
	$template['servicename'] = 'httpd';
	$template['active'] = true;
	$template['file'][] = array('filename' => 'mailman');

	$ret[] = $template;
}

?>
